//
//  PBAddUserInfoCell.m
//  PBHomeDemo
//
//  Created by Playboy on 2018/5/9.
//  Copyright © 2018年 tmkj. All rights reserved.
//

#import "PBAddUserInfoCell.h"
#import "EHSingleChooseViewController.h"
#import "PBAddSeriveCollectCell.h"
#import "TZImagePickerController.h"
#import <Photos/Photos.h>

static NSString * const kPBAddSeriveCollectCell = @"PBAddSeriveCollectCell";

@interface PBAddUserInfoCell ()<UICollectionViewDataSource,UICollectionViewDelegate,TZImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIView *homeView;
@property (weak, nonatomic) IBOutlet UILabel *homeDesLabel;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextView *desTextView;
@property (weak, nonatomic) IBOutlet UIView *addView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint;
@property (nonatomic, strong) NSString       *houseId;
@property (nonatomic, strong) NSMutableArray    *imageArray;

@end

@implementation PBAddUserInfoCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    self.addView.layer.borderWidth = 1.0f;
    self.addView.layer.borderColor = UIColorWithRGB(230, 230, 230).CGColor;
    UITapGestureRecognizer *homeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseHomeInfoMethod)];
    [self.homeView addGestureRecognizer:homeTap];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:kPBAddSeriveCollectCell bundle:nil] forCellWithReuseIdentifier:kPBAddSeriveCollectCell];
}


// 提交

- (IBAction)commitButtonClick:(UIButton *)sender {
    NSString *home = self.homeDesLabel.text;
    if ([home isEqualToString:@"请选择"]) {
        [self showHint:@"请先选择房源"];
        return ;
    }
    NSString *name = self.nameTextField.text;
    NSString *phone = self.phoneTextField.text;
    NSString *des = self.desTextView.text;
    
    NSDictionary *param = @{@"descript":des,
                            @"url":[self.imageArray componentsJoinedByString:@","],
                            @"userName":name,
                            @"phone":phone,
                            @"houseId":self.houseId};
    [TMNetwork requestPostWithParam:param url:@"/repair/saveOrUpdate" callback:^(TMBaseReqModel *model) {
        if (model.code == 200) {
            [self showHint:@"添加报修成功"];
            [self.jumpVC.navigationController popViewControllerAnimated:YES];
        }else {
            [self showHint:model.message];
        }
    }];
    
}

// 房源选择
- (void)chooseHomeInfoMethod {
    NSDictionary *param = @{};
    [TMNetwork requestPostWithParam:param url:@"/user/contract/userHouse" callback:^(TMBaseReqModel *model) {
        if (model.code == 200) {
            NSMutableArray *homes = [[NSMutableArray alloc] init];
            for (NSDictionary *dic in model.data) {
                [homes addObject:dic[@"houseName"]];
            }
            if (homes.count == 0) {
                [self showHint:@"你暂无签约房源"];
                return ;
            }
            
            EHSingleChooseViewController *vc = [[EHSingleChooseViewController alloc] init];
            vc.options = [homes copy];
            [vc setSelectedIndexBlock:^(NSInteger index) {
                self.homeDesLabel.text = homes[index];
                self.houseId = model.data[index][@"houseId"];
                [self.jumpVC.navigationController popViewControllerAnimated:YES];
            }];
            [self.jumpVC.navigationController pushViewController:vc animated:YES];
        }else {
            [self showHint:model.message];
        }
    }];
}


#pragma mark - <UICollectionViewDataSource,UICollectionViewDelegate>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return (self.imageArray.count==5)?5:self.imageArray.count+1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PBAddSeriveCollectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kPBAddSeriveCollectCell forIndexPath:indexPath];
    [cell refreshWithImageArray:self.imageArray indexPath:indexPath];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (self.imageArray.count == 5) {
        return;
    }
    
    TZImagePickerController *pickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:5 delegate:self];
    pickerVc.allowPickingVideo = NO;
    pickerVc.sortAscendingByModificationDate = NO;
    [pickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (assets.count) {
            static PHImageRequestOptions *requestOptions;
            if (!requestOptions) {
                requestOptions = [[PHImageRequestOptions alloc] init];
                requestOptions.synchronous = YES;
                //requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
                requestOptions.resizeMode = PHImageRequestOptionsResizeModeNone;
            }
            NSMutableArray *imageAry = [[NSMutableArray alloc] init];
//            NSMutableArray *imageDesAry = [[NSMutableArray alloc] init];
            for (PHAsset *asset in assets) {
                CGSize size = CGSizeMake(asset.pixelWidth, asset.pixelHeight);
                [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:requestOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                    [imageAry addObject:result];
//                    [imageDesAry addObject:@"添加图片描述"];
                }];
            }

            // 上传图片到服务器获取图片url
//            NSMutableArray *imageDataArray = [[NSMutableArray alloc] init];
            [self.jumpVC showHud];
            for (UIImage *image in imageAry) {
                NSData *imageData = UIImageJPEGRepresentation(image, 0.7f);
                [TMNetwork requestImageWithImage:imageData url:@"/file/upload" callback:^(TMBaseReqModel *model) {
                    if (model.data) {
                        [self.imageArray addObject:model.data];
//                        if (self.imageArray.count > 3) {
//                            self.heightConstraint.constant = 280;
//                        }
                        [self.collectionView reloadData];
                    }
                }];
//                [imageDataArray addObject:imageData];
            }
            
//            [TMNetwork requestImageWithImageArray:imageDataArray callback:^(TMBaseReqModel *model) {
//                [self.jumpVC hideHud];
//                NSLog(@"%@",model.data);
//            }];
            
        }
    }];
    [self.jumpVC presentViewController:pickerVc animated:YES completion:nil];
}

#pragma mark - TZImagePickerControllerDelegate


#pragma mark - <UICollectionViewDelegateFlowLayout>
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((kScreenWidth-100)/3, 80);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}


- (NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [[NSMutableArray alloc] init];
    }
    return _imageArray;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
